<template>
  <div class="student-list">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>学员列表</span>
          <el-button type="primary" @click="handleAdd">新增学员</el-button>
        </div>
      </template>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入学员姓名" clearable :style="{ width: '180px' }" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable :style="{ width: '180px' }" />
        </el-form-item>
        <el-form-item label="学习阶段">
          <el-select v-model="searchForm.stage" placeholder="请选择学习阶段" clearable class="stage-select">
            <el-option label="请选择" value="" />
            <el-option label="科目一" value="1"  />
            <el-option label="科目二" value="2" />
            <el-option label="科目三" value="3" />
            <el-option label="科目四" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" style="width: 100%" v-loading="loading">
       <el-table-column label="头像" width="80">
          <template #default="scope">
            <el-avatar :src="scope.row.avatar" :alt="scope.row.name" size="small">
              <span v-if="!scope.row.avatar">{{ (scope.row.name || '未知').charAt(0) }}</span>
            </el-avatar>
          </template>
        </el-table-column>  
       <el-table-column prop="id" label="学员编号" width="120" /> 
         <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="idCard" label="身份证号" width="180" />
        <el-table-column prop="stage" label="学习阶段" width="120">
          <template #default="scope">
            <el-tag :type="getStageTagType(scope.row.stage)">{{ getStageText(scope.row.stage) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registrationDate" label="报名日期" width="180" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'info'">
              {{ scope.row.status === 0 ? '在学' : '结业' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template> 
        </el-table-column>

      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-drawer
      :title="dialogType === 'add' ? '新增学员' : '编辑学员'"
      v-model="drawerVisible"
      direction="rtl"
      size="45%"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="学习阶段" prop="stage">
          <el-select v-model="form.stage" placeholder="请选择学习阶段" class="stage-select">
            <el-option label="科目一" value="1" />
            <el-option label="科目二" value="2" />
            <el-option label="科目三" value="3" />
            <el-option label="科目四" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="active">在学</el-radio>
            <el-radio label="graduated">结业</el-radio>
          </el-radio-group>
        </el-form-item>
           <el-form-item label="考试日期" prop="examDate">
            <el-date-picker
              v-model="form.registrationDate"
              type="date"
              placeholder="选择日期"
              :disabled-date="() => false"
            />
          </el-form-item>
           
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-drawer>
    
    <!-- 学员详情抽屉 -->
    <el-drawer
      v-model="detailDrawerVisible"
      title="学员详情"
      direction="rtl"
      size="50%"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="学员编号">{{ currentStudent.id }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ currentStudent.name }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentStudent.phone }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ currentStudent.idCard }}</el-descriptions-item>
        <el-descriptions-item label="学习阶段">
          <el-tag :type="getStageTagType(currentStudent.stage)">
            {{ getStageText(currentStudent.stage) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="报名日期">{{ currentStudent.registrationDate }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentStudent.status === 'active' ? 'success' : 'info'">
            {{ currentStudent.status === 'active' ? '在学' : '结业' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 导入API函数
// 请确认 @/api/student 文件是否存在，若不存在需创建该文件并实现以下函数
// 若文件路径有误，请修改为正确路径
// 代码本身导入语法无误，但需确认 @/api/student 文件是否存在且包含对应函数
import { showStudentList, deleteStudentById, addStudent,
   updateStudent, queryStudent } from '@/api/student'

// 获取学员表格数据
const tableData =  ref([
    showStudentList().then((res: any) => {
    tableData.value = res.data
  }).catch(err=>{
    console.log(err)
  })
])
//初始化学员列表
function getStudentList() {
  showStudentList().then((res :any) => {
    loading.value = true
    // 检查响应数据结构是否符合预期

      console.log(res.data) // 调试输出
      tableData.value = res.data // 更新表格数据，tableData 是 ref 对象，使用 value 访问
    loading.value = false
  }).catch(err => {
    console.error('获取学员列表失败', err)
    loading.value = false
  })
}

// 搜索表单
const searchForm = reactive({
  name: '',
  phone: '',
  stage: ''
})

// 表格数据
const loading = ref(false)
//显示所有的表单数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const drawerVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  name: '',
  phone: '',
  idCard: '',
  stage: '',
  status: 'active',
  registrationDate: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  stage: [{ required: true, message: '请选择学习阶段', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 获取学习阶段文本
const getStageText = (stage: string) => {
  const stageMap = {
    '1': '科目一',
    '2': '科目二',
    '3': '科目三',
    '4': '科目四'
  }
  return stageMap[stage as keyof typeof stageMap] || '未知'
}

// 获取学习阶段标签类型
const getStageTagType = (stage: string) => {
  const typeMap = {
    '1': 'info',
    '2': 'warning',
    '3': 'success',
    '4': 'primary'
  }
  return typeMap[stage as keyof typeof typeMap] || ''
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  queryStudent(searchForm.name, searchForm.phone, searchForm.stage).then((res: any) => {
    tableData.value = res.data
  }).catch(err => {
    console.log(err)
  })
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.phone = ''
  searchForm.stage = ''
  handleSearch()
}



// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getStudentList()
}

// 当前页改变
const handleCurrentChange = (val:number) => {
  currentPage.value = val
  getStudentList()
}

// 新增学员
const handleAdd = () => {
  dialogType.value = 'add'
  drawerVisible.value = true
  Object.assign(form, {
    name: '',
    phone: '',
    idCard: '',
    stage: '1',
    status: 'active'
  })
}

// 编辑学员
const handleEdit = (row:any) => {
  dialogType.value = 'edit'
  drawerVisible.value = true
  Object.assign(form, row)
}

// 查看学员详情
const detailDrawerVisible = ref(false)
const currentStudent = ref({
  id:'',
  name: '',
  phone: '',
  idCard: '',
  stage: '',
  status: 'active',
  registrationDate: ''
})

const handleView = (row:any) => {
  currentStudent.value = row
  detailDrawerVisible.value = true
}

// 删除学员
const handleDelete = (row:any) => {
  ElMessageBox.confirm(
    '确认删除该学员信息吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 实现删除逻辑
    loading.value = true
    deleteStudentById(row.id)
      .then(() => {
        ElMessage.success('删除成功')
        getStudentList()
      })
      .catch(err => {
        console.error('删除失败', err)
        ElMessage.error('删除失败，请重试')
      })
      .then(() => {
        loading.value = false
      })
      .catch(() => {
        loading.value = false
      })
  })
  .catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  if (formRef.value) {
    await (formRef.value as any).validate((valid: boolean) => {
      if (valid) {
        // 实现提交逻辑
        loading.value = true
        // 处理状态值，将字符串转换为数字
        const formData = {
          ...form,
          status: form.status === 'active' ? 0 : 1
        }

        const promise = dialogType.value === 'add'
          ? addStudent(formData)
          : updateStudent(formData)

        promise
          .then(() => {
            ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
            drawerVisible.value = false
            getStudentList()
          })
          .catch(err => {
            console.error(dialogType.value === 'add' ? '添加失败' : '修改失败', err)
            ElMessage.error(dialogType.value === 'add' ? '添加失败，请重试' : '修改失败，请重试')
          })
          .then(() => {
            loading.value = false
          }).catch(() => {
            loading.value = false
          })
      }
    })
  }
}

// 初始化
getStudentList()
</script>

<style scoped>
.student-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>